<?php
/**
 * link: http://bbs.52jscn.com
 * copyright: Copyright (c) 2018 人人禾匠商城
 * author: jack_guo
 */

namespace app\forms\mall\export;

use app\core\CsvExport;
use app\forms\mall\statistics\DataForm;
use app\models\Order;

class DataStatisticsExport extends BaseExport
{

    public $type;

    public function fieldsList()
    {
        if ($this->type == 1) {
            return [
                [
                    'key' => 'name',
                    'value' => '商品',
                ],
                [
                    'key' => 'total_price',
                    'value' => '销售额',
                ],
                [
                    'key' => 'num',
                    'value' => '销售量',
                ],
            ];
        } else {
            return [
                [
                    'key' => 'nickname',
                    'value' => '用户',
                ],
                [
                    'key' => 'total_price',
                    'value' => '支付金额',
                ],
                [
                    'key' => 'num',
                    'value' => '购买件数',
                ],
            ];
        }
    }

    public function export($query)
    {
        $list = $query->limit(100)
            ->asArray()
            ->all();

        if ($this->type == 1) {
            $list = Order::getGoods_name($list);
        }
        if ($this->type == 2) {
            foreach ($list as $key => $v) {
                $list[$key]['nickname'] = $v['user']['nickname'];
                $list[$key]['avatar'] = $v['user']['userInfo']['avatar'];
                unset($list[$key]['user']);
            }
        }

        $this->transform($list);
        $this->getFields();
        $dataList = $this->getDataList();

        switch ($this->type) {
            case 1:
                $fileName = '商品购买力排行' . date('YmdHis');
                break;
            case  2:
                $fileName = '用户购买力排行' . date('YmdHis');
                break;
            default:
                $fileName = '购买力排行' . date('YmdHis');
        }
        (new CsvExport())->export($dataList, $this->fieldsNameList, $fileName);
    }

    protected function transform($list)
    {
        $newList = [];
        $arr = [];

        $number = 1;
        foreach ($list as $key => $item) {
            $arr['number'] = $number++;
            $item['total_price'] = floatval($item['total_price']);
            $item['num'] = intval($item['num']);

            $arr = array_merge($arr, $item);


            $newList[] = $arr;
        }
        $this->dataList = $newList;
    }

    protected function getFields()
    {
        $arr = [];
        foreach ($this->fieldsList() as $key => $item) {
            $arr[$key] = $item['key'];
        }
        $this->fieldsKeyList = $arr;
        parent::getFields(); // TODO: Change the autogenerated stub
    }
}
